﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Customer_Profile.eCard.DBDao;
using KVB.Common;
using Customer_Profile.Admin;

namespace Customer_Profile.eCard.CardAccount
{
    public partial class ExpenseCardAccountingAdd : System.Web.UI.Page
    {
        string strCardno = "";
        string strCardbalance = "";
        string strStatus = "";
        string strMessage = "";

        string strUserName = "";
        string strUserID = "";
        string strEntity = "";

        const string UploadDirectory = "~/eCard/tempUpload/";
        const int ThumbnailSize = 100;
        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }

            if (Request["card_no"] != null)
            {
                strCardno = Request["card_no"].ToString().Trim();
                txtCardno.Text = strCardno;                
            }
            
            if (Request["expense_no"] != null)
            {
                hidExpenseno.Value = Request["expense_no"].ToString();
            }

            if (!Page.IsPostBack)
            {
                //添加状态
                if (Request["card_no"] != null)
                {
                    bindBalance();
                    bindCflowType();
                    bindDeals(strCardno);
                    btnSubmit.Enabled = false;
                    btnDelete.Enabled = false;
                }

                //修改状态
                if (Request["expense_no"] != null)
                {
                    btnAction.Enabled = true;
                    btnSubmit.Enabled = true;
                    btnDelete.Enabled = true;
                                       
                    bindCflowType();
                    bindDeals_byExpenseno(Request["expense_no"].ToString());
                    bindAttachList(int.Parse(hidDealno.Value.Trim()));
                }
            }
        }

        private void bindBalance()
        {
            AccountingDao.getCardBalance(strCardno, out strCardbalance, out strStatus, out strMessage);
           
            if (strStatus.Equals("N"))
            {
                lblWarning.Text = strMessage;
            }
            if (strCardbalance.Equals(""))
            {
                card_balance.Text = "不能查询到余额，请联系管理员";
                btnAction.Enabled = false;
                lblWarning.Text = strMessage;
            }
            else
            {
                card_balance.Text = strCardbalance;
            }
        }

        private void bindDeals(string card_no)
        {
            DataSet ds = AccountingDao.getDealsbyCardno(card_no);
            if (ds.Tables[0].Rows.Count > 0)
            {
                gridDeal.DataSource = ds;
                gridDeal.DataBind();
                gridDeal.Selection.SelectRow(0);
            }
        }

        private void bindDeals_byExpenseno(string expense_no)
        {
            DataSet ds = AccountingDao.getDealsbyExpenseno(expense_no);            
            if (!Comm.DataSetIsEmpty(ds))
            {
                hidDealno.Value = ds.Tables[0].Rows[0]["deal_no"].ToString();
                strCardno = ds.Tables[0].Rows[0]["card_no"].ToString();
                txtCardno.Text = strCardno;
                txtAmount.Text = ds.Tables[0].Rows[0]["amount"].ToString();
                rbCflowType.Items.FindByValue(ds.Tables[0].Rows[0]["cflow_type"].ToString()).Selected = true;
                txtRemark.Text = ds.Tables[0].Rows[0]["remark"].ToString();
                txtPass.Text = ds.Tables[0].Rows[0]["pass_remark"].ToString();
                txtBack.Text = ds.Tables[0].Rows[0]["reject_remark"].ToString();

                string str_card_balance;
                AccountingDao.getCardBalance(strCardno, out str_card_balance);
                if (str_card_balance.Equals(""))
                {
                    card_balance.Text = "不能查询到余额，请联系管理员";
                    btnAction.Enabled = false;
                    btnSubmit.Enabled = false;
                    lblWarning.Text = "不能查询到余额，请联系管理员";
                    return;
                }
                else
                {
                    card_balance.Text = str_card_balance;
                }

                bindDeals(strCardno);
                //gridDeal.Selection.SetSelectionByKey(hidDealno.Value, true);
            }
            else
            {
                lblWarning.Text = "获取原始交易失败，请联系管理员！";
            }
        }

        private void bindCflowType()
        {
            CodeDao codeDeoobject = new CodeDao();
            DataSet ds = codeDeoobject.GetList("9");
            rbCflowType.DataSource = ds;
            rbCflowType.DataTextField = "CodeName";
            rbCflowType.DataValueField = "CodeValue";
            rbCflowType.DataBind();

            if (ds.Tables[0].Rows.Count > 0)
            {
                //rbCflowType.SelectedIndex = 0;
                rbCflowType.Items.FindByValue("expense").Selected = true;
            }
        }

        protected void btnAction_Click(object sender, EventArgs e)
        {
            //-1,检查是否锁定，是否存在，等等状况。
            // 0,检查余额是否足够
            // 1,添加expense_deals数据
            // 2,锁定mmdeals交易。            
            string strStatus = "";
            string strMessage = ""; 
            try
            {
                //添加
                if (hidExpenseno.Value.Equals(""))
                {
                    AccountingDao.CardAccountingCheck(strCardno, out strStatus, out strMessage);
                    if (strStatus.Equals("N"))
                    {
                        lblWarning.Text = strMessage;
                        return;
                    }

                    //string attach_url = uploadAttach();
                    int ideal_no = int.Parse(hidDealno.Value.ToString());
                    decimal dcflow_amount = decimal.Parse(txtAmount.Text.Trim());
                    AccountingDao.cardExpenseAdd(strCardno, ideal_no, rbCflowType.SelectedItem.Value, dcflow_amount, txtRemark.Text, strUserID, strUserName, out strStatus, out strMessage);
                    if (strStatus.Equals("N"))
                    {
                        lblWarning.Text = strMessage;
                    }
                    else
                    {
                        KVB.Common.JavaScript.ViewMsgGoUrl("ExpenseCardAccountingAdd.aspx?expense_no=" + strMessage, "消费扣款申请保存成功！");
                    }
                }
                else
                {
                    int ideal_no = int.Parse(hidDealno.Value.ToString());
                    //检查是否锁定，如果未锁定，有问题。
                    //检查交易是否被锁定，如果没锁定，报错，请联系管理员。
                    if (!checkIfLocked(hidExpenseno.Value.Trim()))
                    {
                        //1,锁定，
                        DealDao.LockRefDeals_byDealno(ideal_no.ToString());
                        //2,发一条错误短信给系统管理员。
                        Log.WriteDefaultLog(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：", hidExpenseno.Value);
                        Comm.SendSMS(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：" + hidExpenseno.Value);
                    }

                    decimal dcflow_amount = decimal.Parse(txtAmount.Text.Trim());
                    AccountingDao.cardExpenseUpdate(int.Parse(hidExpenseno.Value), ideal_no, rbCflowType.SelectedItem.Value, dcflow_amount, txtRemark.Text, strUserID, strUserName, out strStatus, out strMessage);
                    if (strStatus.Equals("N"))
                    {
                        lblWarning.Text = strMessage;
                    }
                    else
                    {
                        lblWarning.Text = "修改成功";
                    }
                }
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string view_name = "";
            string attach_name = "";
            string attach_type = "";
            string attach_size = "";
            string attach_url = "";

            FileInfo fileInfo = new FileInfo(FileUpload1.FileName);
            attach_name = DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileInfo.Name;
            string savePathName = MapPath(UploadDirectory) + attach_name;
            FileUpload1.SaveAs(savePathName);

            view_name = fileInfo.Name;
            attach_type = FileUpload1.PostedFile.ContentType.ToString();
            attach_size = FileUpload1.PostedFile.ContentLength / 1024 + "K";
            attach_url = "/eCard/tempUpload/" + attach_name;
            //int ideal_no = int.Parse(hidDealno.Value.ToString());

            AttachDao.AddAttach(int.Parse(hidDealno.Value.Trim()), view_name, attach_name, attach_type, attach_size, attach_url, "EA");
            bindAttachList(int.Parse(hidDealno.Value.Trim()));
        }

        private void bindAttachList(int deal_no)
        {
            try
            {
                int iDeal_no = deal_no;
                DataSet dsAttachList = AttachDao.getAttachList(iDeal_no, "EA");
                gridAttach.DataSource = dsAttachList;
                gridAttach.DataBind();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("ExpenseCardAccountingAdd.bindAttachList", ex.ToString());
                Response.Write(ex.ToString());
            }
        }

        //检查交易是否被锁定，如果没有被锁定，是有问题的。
        private bool checkIfLocked(string ref_expense_no)
        {
            bool if_locked = false;

            DataSet ds = DealDao.getIfLocked_byExpenseno(ref_expense_no);
            if (!Comm.DataSetIsEmpty(ds))
            {
                string if_slocked = ds.Tables[0].Rows[0][0].ToString();
                if (if_slocked.ToUpper().Trim().Equals("Y"))
                    if_locked = true;
                else
                    if_locked = false;
            }
            else
            {
                Log.WriteDefaultLog("checkIfLocked-Expense:" + ref_expense_no + "\r\n", "ds不能为空，如果为空那里出错了");
            }

            return if_locked;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string status = "";
                string message = "";
                int ideal_no = int.Parse(hidDealno.Value.ToString());

                //检查交易是否被锁定，如果没锁定，报错，请联系管理员，发短信给管理员
                if (!checkIfLocked(hidExpenseno.Value.Trim()))
                {
                    //1,锁定，
                    DealDao.LockRefDeals_byDealno(ideal_no.ToString());
                    //2,发一条错误短信给系统管理员。
                    Log.WriteDefaultLog(strUserID + " " + strEntity + " 未锁定交易，重复提交错误记录：", hidExpenseno.Value);
                    Comm.SendSMS(strUserID + " " + strEntity + " 提交结算信息到总部发现未锁定交易，重复提交错误记录：" + hidExpenseno.Value);
                }
                AccountingDao.cardExpenseSubmit(int.Parse(hidExpenseno.Value), out status, out message);
                if (status.Equals("Y"))
                {
                    lblWarning.Text = message;
                    //提交了，转回页面
                    KVB.Common.JavaScript.ViewMsgGoUrl("ExpenseCardSearch.aspx", "数据已经提交成功，请等待总部审核！");
                }
                else
                {
                    lblWarning.Text = message;
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("结算申请提交到交易总部出错了：", ex.ToString());
                Response.Write("系统出错了，请联系系统管理员!<br>" + ex.ToString());
            }
        }

        protected void gridAttach_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            try
            {
                if (e.ButtonID != "Delete") return;
                int attach_id = int.Parse(gridAttach.GetRowValues(e.VisibleIndex, "attach_id").ToString());
                int temp_deal_no = int.Parse(gridAttach.GetRowValues(e.VisibleIndex, "deal_no").ToString());
                AttachDao.DeleteAttach(attach_id);
                bindAttachList(temp_deal_no);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                Log.WriteDefaultLog("settle_application.gridAttach_CustomButtonCallback", ex.ToString());
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //1,解锁
            //2,删除数据
            //3,返回到上一页。
            try
            {
                string status = "";
                string message = "";
                int ideal_no = int.Parse(hidDealno.Value.ToString());

                //检查交易是否被锁定，如果没锁定，报错，请联系管理员，发短信给管理员
                if (!checkIfLocked(hidExpenseno.Value.Trim()))
                {
                    //1,锁定，
                    //DealDao.LockRefDeals_byDealno(ideal_no.ToString());
                    //2,发一条错误短信给系统管理员。
                    Log.WriteDefaultLog(strUserID + " " + strEntity + " 消费交易未锁定原始交易，记录号：", hidExpenseno.Value);
                    Comm.SendSMS(strUserID + " " + strEntity + " 提交结算信息到总部发现未锁定交易，重复提交错误记录：" + hidExpenseno.Value);
                    lblWarning.Text = "交易未锁定，无法删除数据，请联系系统管理员";
                }
                else
                {
                    AccountingDao.cardExpenseDelete(int.Parse(hidExpenseno.Value), out status, out message);
                    if (status.Equals("Y"))
                    {
                        lblWarning.Text = message;
                        //提交了，转回页面
                        KVB.Common.JavaScript.ViewMsgGoUrl("ExpenseCardSearch.aspx", "数据已经删除成功！");
                    }
                    else
                    {
                        lblWarning.Text = message;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("删除数据出错了：", ex.ToString());
                Response.Write("系统出错了，请联系系统管理员!<br>" + ex.ToString());
            }
        }
    }
}